package org.oms.dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.oms.model.pager.Pager;
import org.oms.model.pager.SystemContext;

public class BaseDao<T> implements IBaseDao<T> {
	private SessionFactory sessionFactory;

	@Resource(name = "sessionFactory")
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	/**
	 * 创建一个Class的对象来获取泛型的class
	 */
	private Class<T> clz;

	@SuppressWarnings("unchecked")
	public Class<T> getClz() {
		if (clz == null) {
			clz = (Class<T>) (((ParameterizedType) this.getClass()
					.getGenericSuperclass()).getActualTypeArguments()[0]);
		}
		return clz;
	}

	@Override
	public void add(T t) {
		this.getSession().save(t);
	}

	@Override
	public void delete(int id) {
		this.getSession().delete(this.load(id));
	}

	@Override
	public void update(T t) {
		this.getSession().update(t);
	}

	@SuppressWarnings("unchecked")
	@Override
	public T load(int id) {
		return (T) this.getSession().load(getClz(), id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> list(String hql, Object[] args) {
		Query query = this.getSession().createQuery(hql);
		if (args != null) {
			for (int i = 0; i < args.length; i++) {
				query.setParameter(i, args[i]);
			}
		}
		return query.list();
	}

	@Override
	public List<T> list(String hql) {
		return this.list(hql, null);
	}

	@Override
	public List<T> list(String hql, Object args) {
		return this.list(hql, new Object[] { args });
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pager<T> find(String hql, Object[] args) {
		Pager<T> pages = new Pager<T>();
		int pageOffset = SystemContext.getPageOffset();
		int pageSize = SystemContext.getPageSize();
		Query query = this.getSession().createQuery(hql);
		Query cq = this.getSession().createQuery(getCountHql(hql));
		if (args != null) {
			int index = 0;
			for (Object arg : args) {
				query.setParameter(index, arg);
				cq.setParameter(index, arg);
				index++;
			}
		}
		long totalRecord = (Long) cq.uniqueResult();
		query.setFirstResult(pageOffset);
		query.setMaxResults(pageSize);
		List<T> datas = query.list();
		pages.setDatas(datas);
		pages.setPageOffset(pageOffset);
		pages.setPageSize(pageSize);
		pages.setTotalRecord(totalRecord);
		return pages;
	}

	private String getCountHql(String hql) {
		// 1.获取from 前面的字符串
		String f = hql.trim().substring(0, hql.indexOf("from"));
		// 2.将from前面的字符串替换为select count(*)
		if (f.equals("")) {
			hql = "select count(*) " + hql;
		} else {
			hql = hql.replace(f, "select count(*) ");
		}
		// 3.将fetch 替换为""，因为抓取查询不能使用count(*)
		return hql.replace("fetch", "");
	}

	@Override
	public Pager<T> find(String hql, Object args) {
		return this.find(hql, new Object[] { args });
	}

	@Override
	public Pager<T> find(String hql) {
		System.out.println("hql==="+hql);
		return this.find(hql, null);
	}

}
